const { Add, Update, QueryById, Exec, Execsql_Count, QueryOne} = require('../db/dbhelper');
var { formatDateYear, formatDateTime } = require('../libs/common');
var _ = require('underscore');
var { init, format } = require('../models/accessrecord');
const e = require('express');

//新增
const accessrecordAdd = async function (doc) {
  // 推荐人和游客不创建来访记录
  let fdata = await QueryOne('hzz_peoples',{code: doc.accesscode},'online,isinviter');
  if(!fdata.online || fdata.isinviter){
    return;
  }
  let isdone = await QueryOne('hzz_accessrecords',doc);
  if(isdone){
    Update('hzz_accessrecords', format(doc));
  }else{
    Add('hzz_accessrecords', init(doc));
  }
}

//修改
const accessrecordUpdate = function (doc) {
  return Update('hzz_accessrecords', format(doc));
}

//查询详情
const accessrecordInfoById = function (id) {
  return QueryById('hzz_accessrecords', id);
}

//列表
const accessrecordList = async function (doc) {
  //我的访客
  try {
    let { pcode, pagenum, pagesize } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    if (!pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    let sql = `SELECT * FROM hzz_accessrecords  WHERE pcode='${pcode}' AND length(accesscode)=12`;
    sql += ' ORDER BY createtime DESC,id ASC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let listData = await Exec(sql);//await QueryList_Page('hzz_accessrecords', {pcode: pcode}, null, pagenum || 1, pagesize || 10);
    let peos=[];
    let list=[];
    if(listData && listData.length){
      let codestr = _.compact(_.pluck(listData, 'accesscode')).join(',');
      let execsql = 'SELECT code,nickname,avator,grender,birthday,star,height,education,year_income,position,city FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
    }
    _.map(listData, function (item) {
      let people = _.find(peos, function (po) {
        return po.code == item.accesscode;
      })
      if(people){
        people.birthday = formatDateYear(people.birthday);
        if(people.city){
          people.city = '现居'+people.city.replace('市','');
        }else{
          people.city='';
        }
        if(people.nickname && people.nickname.length>6){
          people.nickname= people.nickname.substr(0,6);
        }
        item.code = item.accesscode;
        item.updatetime = formatDateTime(item.createtime);
        delete item.createtime;

        // 用户没有头像，采用默认头像
        if(!people.avator){
          people.avator = people.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png': 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
        item.accessinfo = people || {};
        list.push(item);
        // 更新消息已读状态
        accessrecordUpdate({id: item.id, isread: 1});
      }
    });

    let total = await Execsql_Count(`SELECT count(1) as total FROM hzz_accessrecords  WHERE pcode='${pcode}' AND length(accesscode)=12`);
    let pagecount = Math.ceil(total/pagesize);
    return {
      code: 0,
      data:{
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

module.exports = {
  accessrecordAdd,
  accessrecordUpdate,
  accessrecordInfoById,
  accessrecordList
}